/**
 * Created by xuzhihan on 2018/1/9.
 */
define(["Vue","VueRouter","jquery"], function(Vue, VueRouter, $){
    "use strict";

    function cloud() {
        this.router = {};
        this.init();
    }
    var _cloud = cloud.prototype;
    //获取Deferred对象
    _cloud.dfd = function(beforeStart){
        return beforeStart ? $.Deferred(beforeStart) : $.Deferred();
    };
    //请求资源
    _cloud.acquire = function(path){
        var arrayPath;
        if(!$.isArray(path)){
            arrayPath = [path];
        }else{
            arrayPath = path;
        }
        var promise = this.dfd(function(dfd){
            require(arrayPath,function(){
                dfd.resolve(Array.prototype.slice.call(arguments));
            },function(error){
                dfd.reject(error);
            });
        }).promise();
        return promise;
    };
    //创建路由设置
    _cloud.createRouter = function(path) {
        var _this = this;
        var html = "text!modules" + path + ".html";
        var js = "modules" + path + ".js";
        var css = "css!modules" + path + ".css";
        var promise = _this.acquire([html,js,css]);
        promise.done(function(result){
            var obj = result[1], content = result[0];
            require(obj.require, function () {
                obj.template = content;
                var _router = [{
                    path: path,
                    component: obj
                }];
                _this.router.addRoutes(_router);
            });
        });
    };
    //初始化
    _cloud.init = function() {
        var _this = this;
        var router = new VueRouter({
            routes: [
                { path: '/', redirect: $("#app").attr("default-page") }
            ]
        });
        _this.router = router;
        _this.router.beforeEach(function(to, from, next){
            _this.createRouter(to.path);
            next();
        });
        Vue.use(VueRouter);
        new Vue({
            router: _this.router
        }).$mount('#app');
    };

    var Cloud = new cloud();
    return Cloud;
});